<template>
    <div class="goods-add-form">
        <div class="section1">
            <div class="pro_info_title" style="text-align: center;">
                <div
                    style="margin-left: 0px; height: 40px;width: 300px; text-align: center;line-height: 40px;float: left;font-weight: bold;">
                    {{ data.po_name }}&nbsp;{{ data.purret_code }}</div>
                <div
                    style="margin: 0 auto; height: 40px;width: 250px; text-align: center;line-height: 40px;float: right;">
                    <el-button plain @click="handleEdit">编辑</el-button>
                    <el-button plain @click="handleDelete">删除</el-button>
                    <el-button plain @click="handAudit">审核</el-button>
                </div>
            </div>
            <hr>

            <!-- 基本信息表格 -->
            <table style="width: 100%; border-collapse: collapse;border: none;">
                <tbody>
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">供应商</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ data.vendor_name }}
                        </td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">供应商编号</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ data.vendor_code }}</td>
                        <td style="padding: 10px 0px; color: #666;">退货仓库</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ cwVaule(data.warehouse_code) }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">关联采购订单</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.po_code }}</td>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">退货时间</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ datetime(data.purret_returntime) }}</td>
                        <!-- <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">退货状态</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ getStateText(data.pu_state) }}</td> -->
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">退货原因</td>
                        <td style="padding: 10px 0px 10px 10px; min-width: 50px;">{{ data.purret_returncause }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">创建人</td>
                        <td style="padding: 10px 0px 10px 10px; min-width: 50px;">{{ data.create_by }}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">备注</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.remark || '无' }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; color: #666;">审核状态</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ getAuditText(data.pu_audit) }}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">审核人</td>
                        <td style="padding: 10px 0px 10px 10px;min-width: 180px;">{{ data.pu_audit_by || '无' }}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">审核时间</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ datetime(data.pu_audit_time) || '无' }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; color: #666;">审核意见</td>
                        <td style="padding: 10px 0px 10px 10px;" colspan="5">{{ data.pu_audit_remark || '无' }}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- 退货明细表格 -->
        <div class="section2">
            <el-table :data="detailsDatas" border style="width: 100%" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
            textAlign: 'center',
            background: '#f5f7fa',
            fontWeight: 'bold',
            position: 'sticky',
            top: 0
        }">
            <el-table-column prop="pro_code" label="产品编号" width="180" />
            <el-table-column prop="pro_name" label="产品名称" />
            <el-table-column prop="pro_brand" label="品牌" />
            <el-table-column prop="pro_model" label="规格型号" />
            <el-table-column prop="unitmeas_id" label="单位">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.unitmeas_id) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="po_number" label="采购数量" />
            <el-table-column prop="podet_inbound_quantity" label="已入库数量" />
            <el-table-column prop="podet_notstocked" label="未入库数量" />
            <el-table-column prop="podet_retqty" label="待退货数量" />
            <el-table-column prop="number_returns" label="退货数量" />
            <!--<el-table-column prop="num" label="退货数量" >
                <template #default="scope">
                    <span>{{ThslValue(scope.row)}}</span>
                </template>
                </el-table-column>-->
        </el-table>

        <div style="height: 40px; line-height: 40px;">
            <div style="display: inline-block; float: left;">合计</div>
            <div style="display: inline-block; float:right">退货总数量：{{ data.sun }}</div>
        </div>

        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button @click="customer_handleClose">关闭</el-button>
        </div>
        </div>
    </div>

    <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
        <template #header>
            <div style="text-align: left; font-size: 16px; font-weight: bold;">
                审核
            </div>
        </template>
        <hr>
        <div style="text-align: left;padding: 10px 0px;">
            <p>审核结果</p>
            <div class="my-2 ml-4">
                <el-radio-group v-model="auditStatus">
                    <el-radio value="1">通过</el-radio>
                    <el-radio value="2">驳回</el-radio>
                </el-radio-group>
            </div>
            <div>
                <p>审核意见</p>
                <el-input v-model="auditOpinion" style="width: 350px;height: 90px;"
                    :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" placeholder="请输入" />
            </div>
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="updateAudit">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, markRaw, inject, watch } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { Delete } from '@element-plus/icons-vue'
import dayjs from 'dayjs';
import { useStore } from 'vuex';

export default {
    setup() {
        const store = useStore();
        const datas = store.state.PO_UpdeteArray

        const router = useRouter();
        const Router = useRouter();
        // const route = useRoute();
        // const datas = JSON.parse(String(route.query.rowData));

        const activeMenu = ref('details');
        const centerDialogVisible = ref(false);
        const auditStatus = ref('1');
        const auditOpinion = ref('');
        const measureOptios = ref([]); // 计量单位
        const userOptions = ref([]); // 用户数据源
        const cwdata = ref([]); // 仓库数据源

        // 退货状态文本转换
        const getStateText = (state) => {
            return state == '0' ? '未退货' : state == '1' ? '已退货' : '未知';
        };

        // 审核状态文本转换
        const getAuditText = (audit) => {
            return audit == '0' ? '未审核' : audit == '1' ? '已通过' : '未知';
        };

        const data = reactive({
            purret_id: '',
            po_id: '',
            purret_code: '',
            vendor_name: '',
            vendor_code: '',
            po_code: '',
            po_name: '',
            warehouse_code: '',
            pu_state: '',
            purret_returncause: '',
            purret_returntime: '',
            create_by: '',
            create_time: '',
            remark: '',
            pu_audit: '',
            pu_audit_by: '',
            pu_audit_time: '',
            pu_audit_remark: '',
            sun: 0, // 退货总计
        });

        const detailsDatas = ref([]); // 存储明细信息

        onMounted(() => {
            getUser();
            CK(); // 查询仓库
            info();
            getMeasure();
        });

        // 查询用户
        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
            }).then((result) => {
                userOptions.value = result.data;
            }).catch(console.error);
        }

        // 查询仓库
        function CK() {
            axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
                headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
            }).then((result) => {
                cwdata.value = result.data;
            }).catch(console.error);
        }

        // 查询计量单位
        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: { dict_type: "db_measure" },
                headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
            }).then((result) => {
                measureOptios.value = result.data;
            }).catch(console.error);
        }

        // 编辑功能
        function handleEdit() {
            if(datas.pu_audit == 0||datas.pu_audit == null){
                store.commit('PO_UpdeteArray', datas)
                router.push({
                path: '/main/Pinv/PuUpdate',
                // query: { rowData: JSON.stringify(datas) }
            });
            }else{
                ElMessage.warning('该退货单已被审核，不可再次编辑！');
            }
        }

        // 审核功能
        function handAudit() {
            if (data.pu_audit == '0' || data.pu_audit == null) {
                centerDialogVisible.value = true;
            } else {
                ElMessage.warning('该退货单已被审核，不可再次审核！');
            }
        }

        // 更新审核状态
        function updateAudit() {
            // 构建符合后端接口要求的数据结构
            const requestData = {
                pu_Order_Dto: {
                    purret_id: data.purret_id,
                    po_id: data.po_id,
                    purret_code: data.purret_code,
                    pu_audit: auditStatus.value, // 审核状态
                    pu_audit_by: localStorage.getItem('userLName'), // 当前用户ID
                    pu_audit_time: new Date().toISOString(), // 当前时间
                    pu_audit_remark: auditOpinion.value,// 审核意见
                    warehouse_code: data.warehouse_code,
                },
                pu_Details_Audit_Dtos: detailsDatas.value.map(item => ({
                    podet_id: item.podet_id,
                    purret_id: item.purret_id,
                    po_code: item.po_code,
                    pro_name: item.pro_name,
                    pro_code: item.pro_code,
                    pro_brand: item.pro_brand,
                    pro_model: item.pro_model,
                    unitmeas_id: item.unitmeas_id,
                    po_number: item.po_number,
                    podet_inbound_quantity: item.podet_inbound_quantity,
                    podet_notstocked: item.podet_notstocked,
                    podet_retqty: item.podet_retqty, // 退货数量
                    number_returns: item.number_returns // 退货数量
                }))
            };

            axios.put("http://localhost:5181/api/Pu/PutPuAudit", requestData, {
                headers: { 
                    authorization: `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json'
                }
            }).then((result) => {
                if (result.data == 1) {
                    centerDialogVisible.value = false;
                    ElMessage.success('审核成功');
                } else if(result.data == 5){
                    ElMessage.error('已入库商品库存数量异常');
                    centerDialogVisible.value = false;
                }
            }).catch(error => {
                console.error(error);
                ElMessage.error('审核失败: ' + (error.response?.data?.message || error.message));
            });
        }

        // function updateAudit() {
        //     axios.put("http://localhost:5181/api/Pu/PutPuAudit", , {
        //         headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        //     }).then((result) => {
        //         if (result.data > 0) {
        //             ElMessage.success('审核成功');
        //             customer_handleClose();
        //         } else {
        //             ElMessage.error('审核失败');
        //         }
        //     }).catch(console.error);
        // }

        // 删除功能
        function handleDelete() {
            // console.log(data.purret_id)
            if(datas.pu_audit == 0||datas.pu_audit == null){ 
                ElMessageBox.confirm(
                    '此操作将删除该退货单信息，是否继续？',
                    '警告',
                    {
                        type: 'warning',
                        icon: markRaw(Delete),
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                    }
                ).then(() => {
                    return axios.put('http://localhost:5181/api/Pu/PutPuDelete', {
                        purret_id: data.purret_id,
                        del_flag: "1"
                    }, {
                        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                    });
                }).then((result) => {
                    if (result.data > 0) {
                        ElMessage.success("删除成功");
                        customer_handleClose();
                    } else {
                        ElMessage.error("删除失败");
                    }
                }).catch(() => {});
            }else{
                ElMessage.warning('该退货单已被审核，不可删除！');
            }
        }

        // 关闭页面
        function customer_handleClose() {
            Router.push({ path: '/main/Pinv/Pu' });
            const targetPath = "/main/Pinv/Pu";

            const closeTab = inject('closeTab');
            if (closeTab) {
                closeTab();
            }

            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "采购退货",
                    name: targetPath,
                    path: targetPath
                });
            }

            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        }

        // 日期格式化
        function datetime(isoTime) {
            if (!isoTime) return '';
            const date = new Date(isoTime);
            return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
        }

        // 仓库名称转换
        function cwVaule(row) {
            if (!row) return "无";
            const parentUser = cwdata.value.find((user) => user.warehouse_code == row);
            return parentUser ? parentUser.warehouse_name : "无";
        }

        // 计量单位转换
        function measureValue(row) {
            if (!row) return "无";
            const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        //计算退货数量
        function ThslValue(row){
            const num = Number(row.podet_retqty) + Number(row.number_returns);
            return num
        }

        // 初始化数据
        function info() {
            data.purret_id = datas.purret_id;
            data.po_id = datas.po_id;
            data.purret_code = datas.purret_code;
            data.vendor_name = datas.vendor_name;
            data.vendor_code = datas.vendor_code;
            data.po_code = datas.po_code;
            data.po_name = datas.po_name;
            data.warehouse_code = datas.warehouse_code;
            data.pu_state = datas.pu_state;
            data.purret_returncause = datas.purret_returncause;
            data.purret_returntime = datetime(datas.purret_returntime);
            data.create_by = datas.create_by;
            data.create_time = datetime(datas.create_time);
            data.remark = datas.remark;
            data.pu_audit = datas.pu_audit;
            data.pu_audit_by = datas.pu_audit_by;
            data.pu_audit_time = datetime(datas.pu_audit_time);
            data.pu_audit_remark = datas.pu_audit_remark;
            data.sun = datas.sun || 0; // 退货总计

            // 设置明细数据
            if (datas.details && datas.details.length > 0) {
                detailsDatas.value = datas.details;
            }
        }

        return {
            data,
            activeMenu,
            centerDialogVisible,
            auditStatus,
            auditOpinion,
            detailsDatas,
            cwdata,
            getStateText,
            getAuditText,
            ThslValue,
            userValue: (userId) => {
                if (!userId) return "无";
                const user = userOptions.value.find(u => u.user_id == userId);
                return user ? user.user_name : "无";
            },
            handleEdit,
            handleDelete,
            customer_handleClose,
            datetime,
            handAudit,
            updateAudit,
            cwVaule,
            measureValue,
            close: () => {
                centerDialogVisible.value = false;
                auditStatus.value = '1';
                auditOpinion.value = '';
            }
        };
    }
}
</script>

<style scoped>
/* 样式保持不变 */
.goods-add-form{
    margin-top: -40px;
}
.section2{
    margin-top: -20px;
}
.section1 {
    padding: 20px;
    height: auto;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.pro_info_title {
    text-align: center;
    width: 100%;
    height: 40px;
}

.button-group {
    position: absolute;
    bottom: 10px;
    right: 64px;
    display: flex;
    gap: 10px;
}
</style>